// SettingsViewModel.kt
package com.example.nutritionmanager.viewModels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.nutritionmanager.ui.theme.AppTheme
import com.example.nutritionmanager.ui.theme.ThemeMode
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class SettingsState(
    val isDarkMode: Boolean = false,
    val notificationsEnabled: Boolean = true,
    val boundEmail: String = "",
    val cacheSize: Float = 28.5f,
    val themeMode: ThemeMode = ThemeMode.SYSTEM
)

@HiltViewModel
class SettingsViewModel @Inject constructor() : ViewModel() {
    private val _uiState = MutableStateFlow(SettingsState())
    val uiState = _uiState.asStateFlow()

    init {
        // 初始化时读取保存的主题设置
        _uiState.update {
            it.copy(
                themeMode = AppTheme.themeMode,
                isDarkMode = when(AppTheme.themeMode) {
                    ThemeMode.LIGHT -> false
                    ThemeMode.DARK -> true
                    ThemeMode.SYSTEM -> isSystemInDarkTheme()
                }
            )
        }
    }

    fun toggleDarkMode(enabled: Boolean) {
        _uiState.update {
            val newMode = if (enabled) ThemeMode.DARK else ThemeMode.LIGHT
            AppTheme.themeMode = newMode
            it.copy(
                isDarkMode = enabled,
                themeMode = newMode
            )
        }
        saveThemePreference()
    }

    fun toggleNotifications(enabled: Boolean) {
        _uiState.update { it.copy(notificationsEnabled = enabled) }
        saveNotificationPreference(enabled)
    }

    fun clearCache() {
        viewModelScope.launch {
            // 模拟清除缓存操作
            _uiState.update { it.copy(cacheSize = 0f) }
            // 实际应调用缓存清理逻辑
            // cacheManager.clearCache()
        }
    }

    fun restoreDefaults() {
        viewModelScope.launch {
            _uiState.update {
                SettingsState().copy(
                    themeMode = ThemeMode.SYSTEM,
                    isDarkMode = isSystemInDarkTheme()
                )
            }
            AppTheme.themeMode = ThemeMode.SYSTEM
            saveThemePreference()
            saveNotificationPreference(true)
        }
    }

    private fun saveThemePreference() {
        // 实际应使用 DataStore 保存设置
        // preferences.saveThemeMode(_uiState.value.themeMode)
    }

    private fun saveNotificationPreference(enabled: Boolean) {
        // 实际应使用 DataStore 保存设置
        // preferences.saveNotificationsEnabled(enabled)
    }

    private fun isSystemInDarkTheme(): Boolean {
        // 实际应从系统获取当前暗色模式状态
        return false // 暂返回固定值，需替换真实逻辑
    }
}
